var resultData = null;

$(function () {
	console.log(GetRequest());
	var user = JSON.parse(GetRequest().param).user;
	console.log("user:"+user);
	$("#breadcrumb").html(JSON.parse(GetRequest().param).breadcrumb)
  //加载layui模块
  layui.use(['laydate', 'form', 'table','laytpl'], function () {
    var laydate = layui.laydate,
      form = layui.form,
      table = layui.table,
      laytpl = layui.laytpl;
    //渲染时间插件
      laydate.render({
        elem: '#startTime'
      })
      laydate.render({
        elem: '#endTime',
      })
    //初始化页面
    $(document).ready(function(){
    	queryData();
        console.log(resultData)
        
      table.render({
        // id:'id',//想要隐藏的列，并在cols中不写这列
        elem: '#table'
        , height: 'full-200'
        , data: resultData
        , cols: [[ //表头
          {field: 'GoodsCode', title: '物品代码',templet:'<div><span title="{{d.GoodsCode}}">{{d.GoodsCode}}</span></div>', width:100 ,fixed: 'left'}
          , {field: 'GoodsName', title: '物品名称',templet:'<div><span title="{{d.GoodsName}}">{{d.GoodsName}}</span></div>',width:100}
          , {field: 'GoodsSpec', title: '规格型号',templet:'<div><span title="{{d.GoodsSpec}}">{{d.GoodsSpec}}</span></div>',width:100}
          , {field: 'BoxUnit', title: '计量单位',width:100}
          , {field: 'WarnValue', title: '提醒时间(倒计时)',width:160,templet: '#titleTpl'}
          , {field: 'Status', title: '状态',width:80}
          , {field: 'UserName', title: '录入人',width:100}
          , {field: 'InputTime', title: '录入时间',width:160,templet:'<div><span title="{{d.InputTime}}">{{d.InputTime==null||d.InputTime==undefined?"":d.InputTime}}</span></div>' }
          , {field: 'UpdateUserName', title: '修改人',width:100 }
          , {field: 'UpdateTime', title: '修改时间',width:160,templet:'<div><span title="{{d.UpdateTime}}">{{d.UpdateTime==null||d.UpdateTime==undefined?"":d.UpdateTime}}</span></div>'}
          ,{fixed: 'right',title: '操作', align:'center',toolbar: '#bar'}
        ]]
        ,done:function () {
      		$(".layui-table-main table tbody").append('<tr><td><input id="showdialog" style="width:90px;" type="text" class="layui-input"></td></tr>')
        }
      })
    })
    
    if(resultData.length == 0){
    	reloadPageTableWithNoData();
    }
    
    //查询按钮的事件，以及查询的参数
    form.on('submit(search)', function (data) {
//      console.log($(data.form).serialize());
    	queryData();
    	if(resultData.length == 0){
    		reloadPageTableWithNoData();
    	}else{
    		reloadPageTable();
    	}
      return false;//必须写
    });
  //返回按钮绑定事件
    $("#back").click(function() {
    	parent.showMenuFn();
		parent.$('#main').empty();
    })
    
    //监听工具条（保存，修改，删除等操作）
    table.on('tool(tabledata)', function(obj){ //注：tool是工具条事件名，tabledata是lay-filter="对应的值"
      var data = obj.data; //获得当前行数据
      console.log(data);
      var layEvent = obj.event; //获得 lay-event 对应的值
//      if(layEvent === 'detail'){ //查看
//        console.log("查看")
//      } else if(layEvent === 'del'){ //删除
//        layer.confirm('真的删除行么', function(index){
//          console.log(data.id);
//          obj.del(); //删除对应行（tr）的DOM结构，并更新缓存
//          layer.close(index);
//          //向服务端发送删除指令
//          // $.ajax({
//          //
//          // })
//        });
//      } else if(layEvent === 'edit'){ //编辑
//        console.log("编辑");
//      }
      var savedata = {
    		  "BillSN" : data.BillSN,
    		  "GoodsID" : data.GoodsID,
    		  "GoodsCode" : data.GoodsCode,
    		  "WarnType" : "0",
    		  "WarnValue" : data.WarnValue=="0"?"1":data.WarnValue,
    		  "UserID" : data.UserID,
    		  "InputTime" : new Date(data.InputTime).format("yyyy-MM-dd hh:mm:ss"),
    		  "UpdateUserID" : data.UpdateUserID,
    		  "UpdateTime" : ""
          }
      if(layEvent === 'save'){
    	  if(data.UserID!=""&&data.UserID!=null&&data.UserID!=undefined){
    		  var params = {
    	  				className : 'TwoLevelStockManager',
    	  				method : 'ModifyStockWarning',
    	  				stockWarningInfo : JSON.stringify(savedata),
    	  				userID : user.Ygid
    	  			}
    	      	  $.ajax({
    	      			type : "post",
    	      			url : getRootPath() + 'api/sendPostRequest',
    	      			dataType : "json",
    	      			contentType: 'application/json',
    	      			data : JSON.stringify(params),
    	      			async : false,
    	      			success : function(data) {
    	      				if (data.issuccess == 0) {
    	      					layer.msg('保存成功！',{time:1000});
        	      				console.log(data.result)
        	      				
        	      				$("#startTime").val("");
        						$("#endTime").val("");
        						$("#goodname").val("");
        						$("#status").val("2");
        	      				
        	      				queryData();
        				    	table.reload("table",{
        				    		data:resultData
        				    	})
    	      				}else{
    	      					layer.msg('保存失败！',{time:1000});
    	      				}
    	      				
    	      			},
    	      			error : function(data) {
    	      				console.log(data.message)
    	      			}
    	      		})
    	  }else{
    		  var params = {
    					className : 'TwoLevelStockManager',
    					method : 'InputStockWarning',
    					stockWarningInfo : JSON.stringify(savedata),
    					userID : user.Ygid
    				}
    	    	  $.ajax({
    	    			type : "post",
    	    			url : getRootPath() + 'api/sendPostRequest',
    	    			dataType : "json",
    	    			contentType: 'application/json',
    	    			data : JSON.stringify(params),
    	    			async : false,
    	    			success : function(data) {
    	    				layer.msg('保存成功！',{time:1000});
    	    				console.log(data.result)
    	    				
    	    				$("#startTime").val("");
    						$("#endTime").val("");
    						$("#goodname").val("");
    						$("#status").val("2");
    						
    						queryData();
    						reloadPageTable();
    	    			},
    	    			error : function(data) {
    	    				console.log(data.message)
    	    			}
    	    		})
    	  }
    	  
    	  
      }
//      else if(layEvent === 'edit'){
//    	  if(data.UserID==""||data.UserID==null||data.UserID==undefined){
//    		  layer.msg('修改失败，请选择保存按钮！',{time:1000});
//    		  return;
//    	  }
//    	  
//      }
      else if(layEvent === 'open'){
    	  if(data.Status == ""||data.Status == null||data.Status == undefined){
    		  layer.msg('数据未保存,无法进行此操作',{time:2000});
    		  return;
    	  }
    	  var params = {
    				className : 'TwoLevelStockManager',
    				method : 'UpdateStockWarningStatus',
    				billSN : data.BillSN,
    				status : "1"
    			}
        	  $.ajax({
        			type : "post",
        			url : getRootPath() + 'api/sendPostRequest',
        			dataType : "json",
        			contentType: 'application/json',
        			data : JSON.stringify(params),
        			async : false,
        			success : function(data) {
        				if (data.issuccess == 0) {
        					layer.msg('已启用！',{time:1000});
            				console.log(data.result)
            				
            				queryData();
            				table.reload("table",{
    				    		data:resultData
    				    	})
        				}else{
        					layer.msg('启用失败！',{time:1000});
        				}
        				
        			},
        			error : function(data) {
        				console.log(data.message)
        			}
        		})
      }else if(layEvent === 'unopen'){
    	  if(data.Status == ""||data.Status == null||data.Status == undefined){
    		  layer.msg('数据未保存,无法进行此操作',{time:2000});
    		  return;
    	  }
    	  var params = {
    				className : 'TwoLevelStockManager',
    				method : 'UpdateStockWarningStatus',
    				billSN : data.BillSN,
    				status : "0"
    			}
        	  $.ajax({
        			type : "post",
        			url : getRootPath() + 'api/sendPostRequest',
        			dataType : "json",
        			contentType: 'application/json',
        			data : JSON.stringify(params),
        			async : false,
        			success : function(data) {
        				if (data.issuccess == 0) {
        					layer.msg('已停用！',{time:1000});
            				console.log(data.result)
            				
            				queryData();
            				table.reload("table",{
    				    		data:resultData
    				    	})
        				}else{
        					layer.msg('停用失败！',{time:1000});
        				}
        				
        			},
        			error : function(data) {
        				console.log(data.message)
        			}
        		})
      }else if(layEvent === 'del'){
    	  layer.confirm('真的删除行么', function(index){
//            console.log(data.id);
//            obj.del(); //删除对应行（tr）的DOM结构，并更新缓存
//            layer.close(index);
            if(data.BillSN!=null){
//              向服务端发送删除指令
                var params = {
    				className : 'TwoLevelStockManager',
    				method : 'DeleteStockWarning',
    				billSN : data.BillSN
    			}
            	$.ajax({
        			type : "post",
        			url : getRootPath() + 'api/sendPostRequest',
        			dataType : "json",
        			contentType: 'application/json',
        			data : JSON.stringify(params),
        			async : false,
        			success : function(data) {
        				if (data.issuccess == 0) {
        					obj.del(); //删除对应行（tr）的DOM结构，并更新缓存
        					layer.close(index);
        					
        					layer.msg('删除成功！',{time:1000});
        					console.log(data.result)
        					
        					$("#startTime").val("");
        					$("#endTime").val("");
        					$("#goodname").val("");
        					$("#status").val("2");
        					
        					queryData();
        					if(resultData.length == 0){
        						reloadPageTableWithNoData();
        					}else{
        						reloadPageTable();
        					}
        				} else{
        					layer.msg('删除失败！',{time:1000});
        				}
        			},
        			error : function(data) {
        				console.log(data.message)
        			}
        		})
            } else{
            	obj.del(); //删除对应行（tr）的DOM结构，并更新缓存
				layer.close(index);
				layer.msg('删除成功！',{time:1000});
            }

          });
      }else{
    	  
      }
    });
  
//    $("body").on("click","#showdialog",function(){
//      layer.open({
//        type: 2,
//        area: ['900px', '400px'],
//        fixed: false, //不固定
//        maxmin: false,
//        title:'物品查询',
//        content: '../view/common.html'
//      });	
//    })
    
    $("body").on("keydown","#showdialog", function (e) {
        if (e.keyCode == 13) {
//        	console.log("1234567890")
            //to-do when click Enter Key
//        	table.cache.table.push({
//        		GoodsID:"LL019070001010",
//        		GoodsCode:"BB001013000000",
//        		GoodsName:"自动折纱布机",
//        		GoodsSpec:"",
//        		BoxUnit:"台",
//        		WarnValue:"180,90,30,0"
//        	});
//        	var data = table.cache.table;
//        	table.reload("table",{
//        		data:data
//        	})
        	parent.$('#goodsSelectWrap').load(getRootPath()+'new/view/GoodsQuery.html')
        }
    });
    
    //获取当前行数据
    getindex=function(idx,value){
//      console.log(table.cache.table[idx]);//改为提醒时间--gg
//      table.cache.table[idx-1].WarnValue = value;
//    	console.log(table.cache.table[idx]);
//        console.log(value)
        table.cache.table[idx-1].WarnValue = value;
    }
    
    window.addEventListener('message',function(e){
    	if(e.source!=window.parent) return;
    	var newBillData = e.data
//    	console.log(e.data)
//    	console.log(table.cache.table)
//    	resultData = table.cache.table;
    	for(var i=0;i<resultData.length;i++){
			if(resultData[i].GoodsCode==newBillData.GoodsCode){
				layer.msg('所选物品已在维护列表，请勿重复添加！',{time:2000});
				return;
			}
		}
    	resultData.push({
    		GoodsID:newBillData.GoodsID,
    		GoodsCode:newBillData.GoodsCode,
    		GoodsName:newBillData.GoodsName,
    		GoodsSpec:newBillData.GoodsSpec,
    		BoxUnit:newBillData.BoxUnit,
    		WarnValue:"0"
    	});
    	reloadPageTable();
    })
    
    
    function reloadPageTableWithNoData(){
    	  table.reload("table",{
    		  data:[{GoodsCode:"",GoodsName:"",GoodsSpec:"",BoxUnit:"",WarnValue:"",Status:"",UserID:"",InputTime:"",UpdateUserID:"",UpdateTime:""}],
    		  cols: [[ //表头
    			  	{field: 'GoodsCode', title: '物品代码',templet:'#input',width:100,},
  	            {field: 'GoodsName', title: '物品名称',width:100,templet:"#bar0"},
  	            {field: 'GoodsSpec', title: '规格型号',width:100,templet:"#bar0"},
  	            {field: 'BoxUnit', title: '计量单位',width:100},
  	            {field: 'WarnValue', title: '提醒时间(倒计时)',width:160,templet:"#bar0"},
  	            {field: 'Status', title: '状态',width:80},
  	            {field: 'UserName', title: '录入人',width:100},
  	            {field: 'InputTime', title: '录入时间',width:160,width:160 },
  	            {field: 'UpdateUserName', title: '修改人',width:100 },
  	            {field: 'UpdateTime', title: '修改时间',width:160,width:160 },
  	            {fixed: 'right',title: '操作', align:'center',toolbar:"#bar0"}
    			  ]],
			  done: function(res, curr, count) {
				  
			  }
    	  })
      }
      
      function reloadPageTable(){
    	  table.reload("table",{
    		  data: resultData,
	          cols: [[ //表头
	            {field: 'GoodsCode', title: '物品代码',templet:'<div><span title="{{d.GoodsCode}}">{{d.GoodsCode}}</span></div>', width:100,},
	            {field: 'GoodsName', title: '物品名称',templet:'<div><span title="{{d.GoodsName}}">{{d.GoodsName}}</span></div>',width:100},
	            {field: 'GoodsSpec', title: '规格型号',templet:'<div><span title="{{d.GoodsSpec}}">{{d.GoodsSpec}}</span></div>',width:100},
	            {field: 'BoxUnit', title: '计量单位',width:100},
	            {field: 'WarnValue', title: '提醒时间(倒计时)',width:160,templet: '#titleTpl'},
	            {field: 'Status', title: '状态',width:80},
	            {field: 'UserName', title: '录入人',width:100},
	            {field: 'InputTime', title: '录入时间',width:160 },
	            {field: 'UpdateUserName', title: '修改人',width:100 },
	            {field: 'UpdateTime', title: '修改时间',width:160 },
	            {fixed: 'right',title: '操作', align:'center',toolbar: '#bar'}
	          ]],
	          done:function () {
	        	  $(".layui-table-main table tbody").append('<tr><td><input id="showdialog" style="width:90px;" type="text" class="layui-input"></td></tr>')
	          }	
    	  })
      }
    
  })
  
})

/**
 * 查询数据
 */
function queryData() {
	var condition = {
		"Conditions" : [ {
			"ColumnName" : "WarnType",
			"FullString" : null,
			"Oper" : "Equal",
			"Value" : "0",
			"Type" : "String"
		} ,{
			"ColumnName" : "a.yxbz",
			"FullString" : null,
			"Oper" : "Equal",
			"Value" : "1",
			"Type" : "String"
		}],
		"Type" : "AND"
	};
	if($("#goodname").val().trim()!=""){
		condition.Conditions.push({
			"ColumnName" : "WZ_Expiry_Stock_Warn.GoodsName",
			"FullString" : null,
			"Oper" : "Like",
			"Value" : "%" + $("#goodname").val() + "%",
			"Type" : "String"
		})
	}
	if($("#startTime").val()!=""){
		condition.Conditions.push({
			"ColumnName" : "InputTime",
			"FullString" : null,
			"Oper" : "MoreOrEqual",
			"Value" : $("#startTime").val(),
			"Type" : "DateTime"
		})
	}
	if ($("#endTime").val()!="") {
		
		condition.Conditions.push({
			"ColumnName" : "InputTime",
			"FullString" : null,
			"Oper" : "LessOrEqual",
			"Value" : $("#endTime").val()+" 23:59:59",
			"Type" : "DateTime"
		})
	}
	if ($("#status").val() != "2") {
		condition.Conditions.push({
			"ColumnName" : "Status",
			"FullString" : null,
			"Oper" : "Equal",
			"Value" : $("#status").val(),
			"Type" : "String"
		})
	}

	var params = {
		className : 'TwoLevelStockManager',
		method : 'GetStockWarnings',
		condition : JSON.stringify(condition),
	}
	$.ajax({
		type : "post",
		url : getRootPath() + 'api/sendPostRequest',
		dataType : "json",
		contentType : 'application/json',
		data : JSON.stringify(params),
		async : false,
		success : function(data) {
			console.log(data.result)
			
			if (data.issuccess == 0) {
				resultData = JSON.parse(data.result);
				for(var i=0;i<resultData.length;i++){
					if(resultData[i].InputTime==null){
						resultData[i].InputTime = "";
					}
					if(resultData[i].UpdateTime==null){
						resultData[i].UpdateTime = "";
					}
					if(resultData[i].Status){
						resultData[i].Status = "启用";
					} else {
						resultData[i].Status = "停用";
					}
				}
			}else{
				layer.msg('查询失败！',{time:3000});
			}
		},
		error : function(data) {
			console.log(data.message)
		}
	})
}